﻿create PROCEDURE Sync.SP_LoanSocialResearchAttachments_ApplyChanges
@RawValues XML 
AS 
BEGIN
	 
		DECLARE @LoanSocialResearchAttachments_Temp TABLE 
		(
			LoanSocialResearchAttachmentID UniqueIdentifier,
			[LoanSocialResearchID] uniqueidentifier,
				[Attachment] uniqueidentifier,
			IsDeleted BIT, 
			LastUpdatedDate DATETIME
		)
		
	   INSERT INTO @LoanSocialResearchAttachments_Temp 
	   SELECT	Tbl.Col.value('LoanSocialResearchAttachmentID[1]','uniqueidentifier') LoanSocialResearchAttachmentID,
                Tbl.Col.value('LoanSocialResearchID[1]', 'uniqueidentifier') [LoanSocialResearchID],
Tbl.Col.value('Attachment[1]', 'uniqueidentifier') [Attachment],
				Tbl.Col.value('IsDeleted[1]', 'bit') IsDeleted,
				Tbl.Col.value('LastUpdatedDate[1]','DateTime') LastUpdatedDate
	   FROM   @RawValues.nodes('/DocumentElement/LoanSocialResearchAttachments') Tbl(Col)
----------------------------------------------------------------------------------------

-- Insert ------------------------------------------------------------------------------

	INSERT INTO [dbo].[LoanSocialResearchAttachments] ([LoanSocialResearchAttachmentID],[LoanSocialResearchID],[Attachment])
	SELECT t.[LoanSocialResearchAttachmentID],t.[LoanSocialResearchID],t.[Attachment]
	FROM  @LoanSocialResearchAttachments_Temp t
	WHERE t.IsDeleted = 0
    AND NOT EXISTS
    (
        SELECT 1 FROM sync.LoanSocialResearchAttachments_Tracking s
        WHERE t.LoanSocialResearchAttachmentID = s.LoanSocialResearchAttachmentID
    )
	-- put conflicts here.
	
-- Update -------------------------------------------------------------------------------
     
	UPDATE [dbo].[LoanSocialResearchAttachments]
	SET [LoanSocialResearchAttachments].[LoanSocialResearchID] = t.[LoanSocialResearchID],[LoanSocialResearchAttachments].[Attachment] = t.[Attachment] 
	FROM [dbo].[LoanSocialResearchAttachments] s JOIN @LoanSocialResearchAttachments_Temp t 
    ON t.LoanSocialResearchAttachmentID = s.LoanSocialResearchAttachmentID
	WHERE	t.IsDeleted = 0 
	AND		t.LastUpdatedDate IS NOT NULL
	AND		t.LastUpdatedDate >= 
				 isnull((SELECT TOP 1 LastUpdatedDate 
				  FROM sync.LoanSocialResearchAttachments_Tracking r
				  WHERE t.LoanSocialResearchAttachmentID = r.LoanSocialResearchAttachmentID)
                  ,t.LastUpdatedDate)
	-----------------------------------------------------------------------------------------

-- Delete -------------------------------------------------------------------------------

	DELETE [dbo].[LoanSocialResearchAttachments]
    FROM @LoanSocialResearchAttachments_Temp t JOIN [dbo].[LoanSocialResearchAttachments] s
    ON t.LoanSocialResearchAttachmentID = s.LoanSocialResearchAttachmentID
	WHERE t.IsDeleted = 1

-----------------------------------------------------------------------------------------
	
END














